package com.rfid.socketio;

import android.content.Context;

import com.rfid.config.ConstantsConfig;
import com.rfid.sockethelper.SocketBase;
import com.rfid.socketio.SocketIOClient;
import com.rfid.webp2plib.BuildConfig;
import com.rfid.webp2plib.SignalClient;
import com.rfid.webp2plib.User;

import java.util.List;

public enum  SocketIoInstance implements SocketBase.OnReceiveListener, SignalClient.UserListener {
    INSTANCE;

    SocketIOClient mSocketIOClient;
    SocketBase.OnReceiveListener mListener;

    String mInfo;
    Context mContext;
    boolean isAutoLogin;

    public void init(Context context,String extraInfo,boolean autoLogin) {
        System.out.println("SocketIoInstance init " +extraInfo);
        mInfo = extraInfo + "_v:" + BuildConfig.buildDate;
        isAutoLogin = autoLogin;
        mContext = context;
        if (mSocketIOClient != null) {
            return;
        }
        mSocketIOClient = new SocketIOClient(this);
        mSocketIOClient.setUserListener(this);
        mSocketIOClient.connectSignalServer();
    }

    public String getVersion() {
        return BuildConfig.buildDate;
    }


    public void release() {
        mContext = null;
        if (mSocketIOClient != null) {
            mSocketIOClient.release();
            mSocketIOClient = null;
        }
    }

    public SocketIOClient getClient() {
        return mSocketIOClient;
    }

    public boolean isConnect() {
        if (mSocketIOClient == null) {
            return false;
        }
        return mSocketIOClient.connected();
    }

    public void setOnReceiveListener(SocketBase.OnReceiveListener listener) {
        mListener = listener;
    }

    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        if (mListener != null) {
            mListener.onReceived(ip,cmd,text);
        }
    }

    @Override
    public void onConnect(String id, boolean connect) {
        if (mListener != null) {
            mListener.onConnect(id,connect);
        }
    }

    @Override
    public void onLogin(String id, List<User> users) {
    }

    @Override
    public void onConnect(String id) {
        if (isAutoLogin) {
            mSocketIOClient.login(mContext, mInfo);
        }
    }

    @Override
    public void onDisconnect() {
    }
}
